package com.haiyou.dc.message;

import com.haiyou.dc.message.constant.OpenfireConstant;
import com.haiyou.dc.message.handler.RedisClient;
import com.haiyou.dc.message.service.PacketService;
import com.haiyou.dc.message.service.impl.MessageServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import org.jivesoftware.openfire.interceptor.InterceptorManager;
import org.jivesoftware.openfire.interceptor.PacketInterceptor;
import org.jivesoftware.openfire.interceptor.PacketRejectedException;
import org.jivesoftware.openfire.session.Session;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import redis.clients.jedis.Jedis;

import java.io.File;

/**
 * @author pc
 */
@Slf4j
public class MessageHandlerPlugin implements Plugin, PacketInterceptor {

    private static Jedis jedis = new Jedis(OpenfireConstant.HOST, OpenfireConstant.PORT);
    private InterceptorManager interceptorManager;

    @Override
    public void initializePlugin(PluginManager pluginManager, File file) {
        this.interceptorManager = InterceptorManager.getInstance();
        this.interceptorManager.addInterceptor(this);
        log.info("jedis start===>{}", jedis);
//        jedis.auth(OpenfireConstant.AUTH);
        new Thread(new RedisClient(jedis)).start();
        log.info("jedis end===>{}", jedis);
    }

    @Override
    public void destroyPlugin() {
        jedis.close();
        log.info("jedis close");
    }

    @Override
    public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException {
        //消息包处理
        if (incoming && !processed) {
            if (packet instanceof Message) {
                PacketService packetService = new MessageServiceImpl();
                packetService.handler(packet, session);
            }
        }
    }
}
